﻿// canvasDrawr originally from Mike Taylr  http://miketaylr.com/
// Tim Branyen massaged it: http://timbranyen.com/
// and i did too. with multi touch.
// and boris fixed some touch identifier stuff to be more specific.

var startDraw = false;
var isInk = 1;
var pixels = new Array();
var canvasId = '';

var CanvasDrawr = function (options) {
    // grab canvas element
    var canvas = document.getElementById(options.id),
        ctxt = canvas.getContext("2d");

    canvas.width = options.width;
    canvas.height = options.height;

    //    canvas.style.width = '100%'
    //    canvas.width = canvas.offsetWidth;
    //    canvas.style.width = '';




    // set props from options, but the defaults are for the cool kids
    ctxt.lineWidth = options.size || Math.ceil(Math.random() * 35);
    ctxt.lineCap = options.lineCap || "round";
    ctxt.pX = undefined;
    ctxt.pY = undefined;

    var lines = [, , ];
    var offset = $(canvas).offset();

    //alert(offset.left + " " + offset.top);
    var self = {
        //bind click events
        init: function () {
            //set pX and pY from first click
            canvas.addEventListener('touchstart', self.preDraw, false);
            canvas.addEventListener('touchmove', self.draw, false);
            canvas.addEventListener('touchend', self.endDraw, false);
        },

        preDraw: function (event) {

            $.each(event.touches, function (i, touch) {

                var id = touch.identifier,
                //colors = ["red", "green", "yellow", "blue", "magenta", "orangered"],
                //mycolor = colors[Math.floor(Math.random() * colors.length)];
                mycolor = 'green';


                lines[id] = { x: this.pageX - offset.left,
                    y: this.pageY - offset.top,
                    color: mycolor
                };

                startDraw = true;
                coOordinates = "" + isInk;
                //alert(lines[id].x + " " + lines[id].y);
            });

            event.preventDefault();
        },

        draw: function (event) {
            var e = event, hmm = {};

            $.each(event.touches, function (i, touch) {
                var id = touch.identifier,
                    moveX = this.pageX - offset.left - lines[id].x,
                    moveY = this.pageY - offset.top - lines[id].y;

                var ret = self.move(id, moveX, moveY);
                if (startDraw) {
                    var xx = this.pageX;
                    var yy = this.pageY;
                    coOordinates += "#" + xx + "," + yy;
                }

                lines[id].x = ret.x;
                lines[id].y = ret.y;
            });

            event.preventDefault();
        },

        endDraw: function (event) {
            startDraw = false;
            if (coOordinates.length > 500) {
                splitPoints = coOordinates.split('#');
                newCoordinates = "" + isInk;
                for (i = 1; i < splitPoints.length; i++) {
                    newCoordinates += "#" + splitPoints[i];
                    if (newCoordinates.length > 50) {
                        newCoordinates = newCoordinates;
                        pixels.push(newCoordinates.toString());
                        newCoordinates = "" + isInk;
                        i -= 2;
                    }
                }
                if (i >= splitPoints.length) {
                    newCoordinates = newCoordinates;
                    pixels.push(newCoordinates.toString());
                    newCoordinates = "" + isInk;
                }
                $("#" + options.id).trigger("drawmultiple", pixels);
            }
            else {
                coOordinates = coOordinates;
                $("#" + options.id).trigger("draw", coOordinates);
                coOordinates = "" + isInk;
            }
        },

        move: function (i, changeX, changeY) {
            ctxt.strokeStyle = lines[i].color;
            ctxt.beginPath();
            ctxt.moveTo(lines[i].x, lines[i].y);

            ctxt.lineTo(lines[i].x + changeX, lines[i].y + changeY);
            ctxt.stroke();
            ctxt.closePath();

            return { x: lines[i].x + changeX, y: lines[i].y + changeY };
        }
    };

    return self.init();
};


//$(function(){
//  var super_awesome_multitouch_drawing_canvas_thingy = new CanvasDrawr({id:"example", size: 15 }); 
//});


var currentIndex = 0;

function InitializeWhiteBoard(drawingCanvas, size, w, h) {
    var super_awesome_multitouch_drawing_canvas_thingy = new CanvasDrawr({ id: drawingCanvas, size: size, width: w, height: h });
    canvasId = drawingCanvas;
    //接收从服务器发来的消息
    $('#' + drawingCanvas).bind("message", function (event, data) {
        DrawPoints(data);
        if (currentIndex < pixels.length - 1) {
            currentIndex++;
            sendPixelMessage(pixels[currentIndex]);
        }
        else {
            currentIndex = 0;
            pixels = new Array();
        }
    });

    //var canvas = document.getElementById(drawingCanvas);
    $('#' + drawingCanvas).bind("draw", function (event, xy) {
        sendPixelMessage(xy);
    });

    $('#' + drawingCanvas).bind("drawmultiple", function (event, xy) {
        currentIndex = 0;
        sendPixelMessage(pixels[currentIndex]);
    });

}

function DrawPoints(jsondata) {
    //var obj = jQuery.parseJSON(jsondata);
    var obj = jsondata;
    var user = obj.user;
    var type = obj.type;
    var data = obj.data;

    var canvas = document.getElementById(canvasId);
    var context = canvas.getContext("2d");
    context.beginPath();

    var allxy = obj.split('#'); //data.split('#');
    if (allxy.length > 1) {
        //        var ink = allxy[0];
        //        if (ink == "1") {
        //            //setInk();
        //            $(this).attr("src", "Images/pencil.jpg");
        //            $(this).attr("title", "Click to select Eraser");
        //        }
        //        else {
        //            //setEraser();
        //            $(this).attr("src", "Images/eraser.gif");
        //            $(this).attr("title", "Click to select Pencil");
        //        }
        for (i = 1; i < allxy.length; i++) {
            xy = allxy[i];
            if (xy != "") {
                DrawPoint(xy);
            }
        }
    }
}

function DrawPoint(data) {

    var canvas = document.getElementById(canvasId);
    var context = canvas.getContext("2d");

    xy = data.split(",");
    x = xy[0];
    y = xy[1];

    context.lineTo((x), (y));
    context.stroke();
}

var socket = null;
function reset() {
    if (socket) {
        socket.close();
    }
    socket = null;
}

function connect() {
    reset();
    var url = 'http://' + commLib.HOST + ':' + commLib.PORT;
    socket = io.connect(url);

    socket.on('connect', function () {
        //alert('ok');
        //        socket.emit('message', JSON.stringify({
        //            'EVENT': EVENT_TYPE.LOGIN,
        //            'values': [currentUserNick]
        //        }));
    });
    var obj;
    socket.on("message", function (message) {
        var mData = commLib.analyzeMessageData(message);
        if (mData && mData.EVENT) {
            switch (mData.EVENT) {
                case commLib.EVENT_TYPE.LOGIN: // 新用户连接                   
                    break;

                case commLib.EVENT_TYPE.LOGOUT: // 用户退出
                    break;

                case commLib.EVENT_TYPE.PIXEL: // 同步画笔
                    obj = mData.values[0];
                    $('#' + canvasId).trigger("message", obj);
                    break;
                case commLib.EVENT_TYPE.SYNC: // 同步请求
                    //接收到服务器发来的控制信息
                    obj = mData.values[0];
                    Ext.Msg.confirm('提示', '主讲人请求同步，是否同意?', function (button) {
                        if (button == 'yes') {
                            //如果同意则跳转到文档同步界面
                            //alert(obj);
                            var v = Ext.create('MyApp.view.MeetingSyncSub');
                            Ext.Viewport.add(v);
                            Ext.Viewport.setActiveItem(v);
                            var w = Ext.getCmp('imageSubContent').element.getWidth(),
                            h = Ext.getCmp('imageSubContent').element.getHeight();
                            InitializeWhiteBoard('canvasSubImage', 4, w, h);

                            var canvas = document.getElementById('canvasSubImage');
                            canvas.width = w;
                            canvas.height = h;
                            var ctxt = canvas.getContext("2d");
                            var img = new Image();
                            img.src = obj;
                            img.onload = function () {
                                ctxt.drawImage(img, 0, 0, canvas.width, canvas.height);
                            }
                        }
                    });
                    break;
                case commLib.EVENT_TYPE.PAGE: // 跳页消息
                    //跳转到新页面                
                    obj = mData.values[0];
                    var canvas = document.getElementById('canvasSubImage');
                    canvas.width = Ext.getCmp('imageSubContent').element.getWidth();
                    canvas.height = Ext.getCmp('imageSubContent').element.getHeight();
                    var ctxt = canvas.getContext("2d");
                    var img = new Image();
                    img.src = obj;
                    img.onload = function () {
                        ctxt.drawImage(img, 0, 0, canvas.width, canvas.height);
                    }
                    break;
                case commLib.EVENT_TYPE.ERROR: // 出错了
                    alert("[系统繁忙...]");
                    break;

                default:
                    break;
            }

        }
    });

    socket.on("error", function (e) {
        //alert("[网络出错啦，请稍后重试...]");
    });


    socket.on("close", function () {
        //alert("[网络连接已被关闭...]");
        close();
    });
}


function getJsonMessage(action, message) {
    var data = JSON.stringify({
        'EVENT': action, //EVENT_TYPE.SPEAK,
        'values': [message]
    });
    return data;
}

function sendPixelMessage(message) {
    var jsonMessage = getJsonMessage(commLib.EVENT_TYPE.PIXEL, message);
    socket.emit('message', jsonMessage);
}


function sendSyncMessage(message) {
    var jsonMessage = getJsonMessage(commLib.EVENT_TYPE.SYNC, message);
    socket.emit('message', jsonMessage);
}


function sendPageMessage(message) {
    var jsonMessage = getJsonMessage(commLib.EVENT_TYPE.PAGE, message);
    socket.emit('message', jsonMessage);
}

function sendClearMessage() {

}
